<?php
declare(strict_types=1);

namespace app\controller\admin;

use app\BaseController;
use app\model\{Role, Admin};
use think\facade\{Db, Log};
use think\Request;

class RoleController extends BaseController
{
    /**
     * 获取角色列表
     */
    public function list(Request $request)
    {
        $where = [];
        
        // 状态筛选
        if ($status = $request->param('status')) {
            $where[] = ['status', '=', $status];
        }
        
        $list = Role::where($where)
            ->field('id, role_name, role_desc, status, create_time, update_time')
            ->order('id', 'asc')
            ->select();
            
        return $this->success('获取成功', $list);
    }
    
    /**
     * 创建角色
     */
    public function add(Request $request)
    {
        $data = $this->validate($request->post(), [
            'role_name' => 'require|max:50',
            'role_desc' => 'max:200',
            'permissions' => 'require|array'
        ]);
        
        Db::startTrans();
        try {
            // 检查角色名是否存在
            if (Role::where('role_name', $data['role_name'])->find()) {
                throw new \Exception('角色名已存在');
            }
            
            // 创建角色
            $role = Role::create([
                'role_name' => $data['role_name'],
                'role_desc' => $data['role_desc'] ?? '',
                'permissions' => json_encode($data['permissions']),
                'status' => 1,
                'create_time' => date('Y-m-d H:i:s')
            ]);
            
            // 记录操作日志
            $this->recordOperationLog('新增', '创建角色：' . $data['role_name']);
            
            Db::commit();
            return $this->success('创建成功', $role);
        } catch (\Exception $e) {
            Db::rollback();
            Log::error('创建角色失败: ' . $e->getMessage());
            return $this->error($e->getMessage());
        }
    }
    
    /**
     * 更新角色
     */
    public function update(Request $request, $id)
    {
        $data = $this->validate($request->post(), [
            'role_name' => 'require|max:50',
            'role_desc' => 'max:200',
            'permissions' => 'require|array',
            'status' => 'require|in:0,1'
        ]);
        
        Db::startTrans();
        try {
            $role = Role::find($id);
            if (!$role) {
                throw new \Exception('角色不存在');
            }
            
            // 检查角色名是否重复
            if ($role->role_name != $data['role_name']) {
                if (Role::where('role_name', $data['role_name'])->find()) {
                    throw new \Exception('角色名已存在');
                }
            }
            
            // 更新角色
            $role->save([
                'role_name' => $data['role_name'],
                'role_desc' => $data['role_desc'] ?? '',
                'permissions' => json_encode($data['permissions']),
                'status' => $data['status'],
                'update_time' => date('Y-m-d H:i:s')
            ]);
            
            // 记录操作日志
            $this->recordOperationLog('修改', '更新角色：' . $data['role_name']);
            
            Db::commit();
            return $this->success('更新成功');
        } catch (\Exception $e) {
            Db::rollback();
            Log::error('更新角色失败: ' . $e->getMessage());
            return $this->error($e->getMessage());
        }
    }
    
    /**
     * 删除角色
     */
    public function delete(Request $request, $id)
    {
        Db::startTrans();
        try {
            $role = Role::find($id);
            if (!$role) {
                throw new \Exception('角色不存在');
            }
            
            // 检查是否有管理员使用此角色
            if (Admin::where('role_id', $id)->find()) {
                throw new \Exception('该角色下存在管理员，无法删除');
            }
            
            // 删除角色
            $role->delete();
            
            // 记录操作日志
            $this->recordOperationLog('删除', '删除角色：' . $role->role_name);
            
            Db::commit();
            return $this->success('删除成功');
        } catch (\Exception $e) {
            Db::rollback();
            Log::error('删除角色失败: ' . $e->getMessage());
            return $this->error($e->getMessage());
        }
    }
    
    /**
     * 获取权限列表
     */
    public function permissions()
    {
        $permissions = [
            [
                'id' => 'dashboard',
                'title' => '控制台',
                'path' => '/dashboard',
                'children' => [
                    ['id' => 'dashboard:view', 'title' => '查看数据', 'path' => '/dashboard/index']
                ]
            ],
            [
                'id' => 'order',
                'title' => '订单管理',
                'path' => '/order',
                'children' => [
                    ['id' => 'order:list', 'title' => '订单列表', 'path' => '/order/index'],
                    ['id' => 'order:detail', 'title' => '订单详情', 'path' => '/order/detail'],
                    ['id' => 'order:export', 'title' => '订单导出', 'path' => '/order/export'],
                    ['id' => 'order:cancel', 'title' => '取消订单', 'path' => '/order/cancel'],
                    ['id' => 'order:refund', 'title' => '订单退款', 'path' => '/order/refund']
                ]
            ],
            [
                'id' => 'merchant',
                'title' => '商家管理',
                'path' => '/merchant',
                'children' => [
                    ['id' => 'merchant:list', 'title' => '商家列表', 'path' => '/merchant/index'],
                    ['id' => 'merchant:add', 'title' => '添加商家', 'path' => '/merchant/add'],
                    ['id' => 'merchant:edit', 'title' => '编辑商家', 'path' => '/merchant/edit'],
                    ['id' => 'merchant:delete', 'title' => '删除商家', 'path' => '/merchant/delete'],
                    ['id' => 'merchant:recharge', 'title' => '充值管理', 'path' => '/merchant/recharge'],
                    ['id' => 'merchant:withdraw', 'title' => '提现管理', 'path' => '/merchant/withdraw']
                ]
            ],
            [
                'id' => 'express',
                'title' => '快递管理',
                'path' => '/express',
                'children' => [
                    ['id' => 'express:company', 'title' => '快递公司', 'path' => '/express/company'],
                    ['id' => 'express:price', 'title' => '价格管理', 'path' => '/express/price'],
                    ['id' => 'express:template', 'title' => '运费模板', 'path' => '/express/template']
                ]
            ],
            [
                'id' => 'config',
                'title' => '系统配置',
                'path' => '/config',
                'children' => [
                    ['id' => 'config:basic', 'title' => '基础配置', 'path' => '/config/basic'],
                    ['id' => 'config:payment', 'title' => '支付配置', 'path' => '/config/payment'],
                    ['id' => 'config:sms', 'title' => '短信配置', 'path' => '/config/sms'],
                    ['id' => 'config:storage', 'title' => '存储配置', 'path' => '/config/storage'],
                    ['id' => 'config:express', 'title' => '快递配置', 'path' => '/config/express']
                ]
            ],
            [
                'id' => 'admin',
                'title' => '管理员',
                'path' => '/admin',
                'children' => [
                    ['id' => 'admin:list', 'title' => '管理员列表', 'path' => '/admin/index'],
                    ['id' => 'admin:add', 'title' => '添加管理员', 'path' => '/admin/add'],
                    ['id' => 'admin:edit', 'title' => '编辑管理员', 'path' => '/admin/edit'],
                    ['id' => 'admin:delete', 'title' => '删除管理员', 'path' => '/admin/delete'],
                    ['id' => 'admin:role', 'title' => '角色管理', 'path' => '/admin/role']
                ]
            ]
        ];
        
        return $this->success('获取成功', $permissions);
    }
    
    /**
     * 记录操作日志
     */
    protected function recordOperationLog($type, $content)
    {
        Db::name('platform_operation_log')->insert([
            'admin_id' => request()->adminId,
            'operation_type' => $type,
            'operation_content' => $content,
            'create_time' => date('Y-m-d H:i:s')
        ]);
    }
} 